/*
 * **************************************************************************
 * *                                                                        *
 * * Ericsson hereby grants to the user a royalty-free, irrevocable,        *
 * * worldwide, nonexclusive, paid-up license to copy, display, perform,    *
 * * prepare and have prepared derivative works based upon the source code  *
 * * in this sample application, and distribute the sample source code and  *
 * * derivative works thereof and to grant others the foregoing rights.     *
 * *                                                                        *
 * * ERICSSON DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,        *
 * * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.       *
 * * IN NO EVENT SHALL ERICSSON BE LIABLE FOR ANY SPECIAL, INDIRECT OR      *
 * * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS    *
 * * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE  *
 * * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE *
 * * OR PERFORMANCE OF THIS SOFTWARE.                                       *
 * *                                                                        *
 * **************************************************************************
 */

package chat;

import com.ericsson.hosasdk.api.HOSAMonitor;
import com.ericsson.hosasdk.api.fw.P_UNKNOWN_SERVICE_TYPE;
import com.ericsson.hosasdk.api.hmm.hus.IpHosaUserStatus;
import com.ericsson.hosasdk.api.hui.IpHosaUIManager;
import com.ericsson.hosasdk.utility.framework.FWproxy;
import com.ericsson.nrgsdk.examples.tools.SDKToolkit;

/**
 * This class implements the logic of the application. It uses processors to
 * interact with Ericsson Network Resource Gateway.
 */
public class Feature {

	private FWproxy itsFramework;

	private IpHosaUIManager itsHosaUIManager;

	private IpHosaUserStatus itsHosaUSManager;

	private SMSProcessor itsSMSProcessor;

	private UserStatusProcessor itsUserStatusProcessor;
        
        private Analizator analizator;

	/**
	 * Initializes a new instance, without starting interaction with NRG (see
	 * start)
	 * 
	 * @param aGUI
	 *            the GUI of the application
	 */
	public Feature(GUI aGUI) {
		aGUI.setTitle("GroupSMS");
		aGUI.addTab("Description", getDescription());
	}

	/**
	 * Starts interaction with the Ericsson Network Resource Gateway. Note: this
	 * method is intended to be called at most once.
	 */
	protected void start() {
                analizator = new Analizator();
		HOSAMonitor.addListener(SDKToolkit.LOGGER);
		System.out.println("Getting framework");
		itsFramework = new FWproxy(Configuration.INSTANCE);
		System.out.println("Getting service managers");
        try
        {
            itsHosaUIManager = (IpHosaUIManager) itsFramework.obtainSCF("SP_HOSA_USER_INTERACTION");
            itsHosaUSManager = (IpHosaUserStatus) itsFramework.obtainSCF("SP_HOSA_USER_STATUS");
        }
        catch (P_UNKNOWN_SERVICE_TYPE anException)
        {
            System.err.println("Service not found. Please refer to the Ericsson Network Resource Gateway User Guide for "
                            + "a list of which applications that are able to run on which test tools\n"
                            + anException);
        }
        System.out.println("Creating processors");
		itsSMSProcessor = new SMSProcessor(itsHosaUIManager, this);
		itsUserStatusProcessor = new UserStatusProcessor(itsHosaUSManager);
		System.out.println("Starting SMS notifications");
		Configuration.Group[] groups = new Configuration.Group[]{new Configuration.Group("2222", new String[]{"10123","10456"}, null)};
		for (int i = 0; i < groups.length; i++) {
			groups[i].assignmentId = new Integer(itsSMSProcessor
					.startNotifications(groups[i].address));
		}
	}

	/**
	 * Stops interaction with the Ericsson Network Resource Gateway and disposes
	 * of all resources allocated by this instance. Note: this method is
	 * intended to be called at most once.
	 */
	public void stop() {
		System.out.println("Stopping SMS notifications");
		Configuration.Group[] groups = new Configuration.Group[]{new Configuration.Group("2222", new String[]{"10123","10456"}, null)};
		for (int i = 0; i < groups.length; i++) {
			Integer assignmentId = groups[i].assignmentId;
			if (assignmentId != null) {
				itsSMSProcessor.stopNotifications(assignmentId.intValue());
				groups[i].assignmentId = null;
			}
		}
		System.out.println("Disposing processors");
		if (itsSMSProcessor != null) {
			itsSMSProcessor.dispose();
		}
		if (itsUserStatusProcessor != null) {
			itsUserStatusProcessor.dispose();
		}
		System.out.println("Disposing service managers");
		if (itsHosaUIManager != null) {
			itsFramework.releaseSCF(itsHosaUIManager);
		}
		if (itsHosaUSManager != null) {
			itsFramework.releaseSCF(itsHosaUSManager);
		}
		System.out.println("Disposing framework");
		if (itsFramework != null) {
			itsFramework.endAccess();
			itsFramework.dispose();
		}
		HOSAMonitor.removeListener(SDKToolkit.LOGGER);
	}

	/**
	 * Invoked by the SMSProcessor, when a notification is received. This method
	 * will request the status of all groupmembers of the group where the SMS
	 * was sent to (aReceiver). Once a status is reachable the SMS will be sent
	 * to that groupmember. If no group members are reachable, a SMS reporting
	 * this will be sent to the sender (aSender).
	 * 
	 * @param aSender
	 *            the sender of the SMS message
	 * @param aReceiver
	 *            the receiver of the SMS message
	 * @param aMessageContent
	 *            the content of the SMS message sent
	 */
	public void smsReceived(String aSender, String aReceiver,
			String aMessageContent) {
            
                 analizator.analizuj(aSender,aReceiver,aMessageContent, itsSMSProcessor);
            //Dodac funkcje analizujaca tresc wiadomosci
            
//		System.out.println("An SMS was received for group '" + aReceiver + "'");
//		Configuration.Group group = findGroup(aReceiver);
//		String reachableAddress = itsUserStatusProcessor
//				.findReachableAddress(group.members);
//		if (reachableAddress != null) {
//			System.out.println("An SMS for group '" + aReceiver
//					+ "' is forwarded to member '" + reachableAddress + "'");
//			itsSMSProcessor.sendSMS(aSender, reachableAddress, aMessageContent);
//		} else {
//			System.out.println("An SMS for group '" + aReceiver + "' bounces");
//			itsSMSProcessor.sendSMS(aReceiver, aSender,
//					"No group member is reachable at the moment.");
//		}
	}

	private Configuration.Group findGroup(String anAddress) {
		Configuration.Group[] groups = new Configuration.Group[]{new Configuration.Group("2222", new String[]{"10123","10456"}, null)};
		for (int i = 0; i < groups.length; i++) {
			if (anAddress.equals(groups[i].address)) {
				return groups[i];
			}
		}
		throw new RuntimeException("Group not found.");
	}

	/**
	 * @return a descriptive text that explains the application and its
	 *         configuration.
	 */
	private String getDescription() {
		String s = "Press START to connect to the Framework"
				+ " and request the H-OSA User Status (H-OSA US) and Messaging services from the Framework.\n";
		s += "Using Messaging, the application then requests to be notified whenever an SMS is sent to a group. ";
		s += "\n";
		s += "Upon notification, the application uses H-OSA US to determine the first group member that is reachable. ";
		s += "Using Messaging again, the SMS is forwarded to this reachable subscriber. ";
		s += "If all group members are unreachable, an SMS is returned to the sending subscriber.\n";
		s += "\n";
		s += "Press STOP to release resources in the Ericsson Network Resource Gateway and the application.\n";
		s += "\n";
		s += "The following groups are configured:\n";
		Configuration.Group[] groups = new Configuration.Group[]{new Configuration.Group("2222", new String[]{"10123","10456"}, null)};
		for (int i = 0; i < groups.length; i++) {
			s += "- group " + SDKToolkit.OBJECTWRITER.print(groups[i].address);
			String[] members = groups[i].members;
			s += " with members " + SDKToolkit.OBJECTWRITER.print(members);
			s += "\n";
		}
		return s;
	}
}
